package ex03.connector;

import ex03.connector.http.HttpResponse;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @packgeName: ex03.connector
 * @ClassName: ResponseStream
 * @copyright: CopyLeft
 * @description:<描述>
 * @author: lili
 * @date: 2017/8/29-12:57
 * @version: 1.0
 * @since: JDK 1.8
 */
public class ResponseStream extends ServletOutputStream{

    protected boolean closed = false;

    protected boolean commit = false;

    protected int count = 0;

    protected int length = -1;

    protected HttpResponse response = null;

    protected OutputStream stream = null;


    public ResponseStream(HttpResponse response) {
        super();
        closed = false;
        commit = false;
        count = 0;
        this.response = response;
    }

    public boolean getCommit() {

        return (this.commit);

    }

    public void setCommit(boolean commit) {
        this.commit = commit;
    }

    @Override
    public void close() throws IOException {
        if(closed){
            throw new IOException("responseStream.close.closed");
        }
        response.flushBuffer();
        closed = true;
    }

    @Override
    public void write(int b) throws IOException {
        if(closed){
            throw new IOException("responseStream.write.closed");
        }
        if((length>0) && (count>=length)){
            throw new IOException("responseStream.write.count");
        }
        response.write(b);
        count++;
    }
}
